package com.ats.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ats.model.User;
import com.ats.service.InstructorService_xh;
import com.ats.service.StudentService_xh;
import com.ats.service.TeacherService_xh;
import com.ats.service.UserSerivce_xh;
import com.ats.serviceimpl.InstructorServiceImpl_xh;
import com.ats.serviceimpl.StudentServiceImpl_xh;
import com.ats.serviceimpl.TeacherServiceImpl_xh;
import com.ats.serviceimpl.UserServiceImpl_xh;
/**
 * 登录
 * @author xh
 *
 */
public class LoginController_xh extends HttpServlet{
	UserSerivce_xh us = new UserServiceImpl_xh();
	InstructorService_xh inss = new InstructorServiceImpl_xh();
	StudentService_xh stus = new StudentServiceImpl_xh();
	TeacherService_xh teas = new TeacherServiceImpl_xh();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//设置字符集
		resp.setCharacterEncoding("utf8");
		HttpSession session =req.getSession();
		PrintWriter  pw = resp.getWriter();
		//获取账户密码
		String uname =req.getParameter("uname");
		String upsw =req.getParameter("upsw");
		//将user的内容放在user对象里面
		User user =us.getUserByNameAndPsw(uname, upsw);
		if(user.getUid()!=0){
			//获取Cookie,设置“记住我”的时间
//			if("on".equals(req.getParameter("remember"))){
//				Cookie  c1 = new Cookie("uname", uname);
//				c1.setMaxAge(60*60);
//				Cookie  c2 = new Cookie("upsw",  upsw);
//				c2.setMaxAge(60*60);
//				resp.addCookie(c1);
//				resp.addCookie(c2);
//			}
		session.setAttribute("user", user);
		//获取老师名字通过 老师id
		int tid =((User)session.getAttribute("user")).getTid();
		String tname =teas.FindTnameByTid(tid);
		session.setAttribute("tname", tname);
		//获取学生名字通过 学生id
		int sid =((User)session.getAttribute("user")).getSid();
		String sname =stus.FindSnameBySid(sid);
		session.setAttribute("sname", sname);
		//获取辅导员名字通过 辅导员id
		int iid =((User)session.getAttribute("user")).getIid();
		String iname =inss.FindInameByIid(iid);
		session.setAttribute("iname", iname);
		//获取当前用户
		boolean flag = us.FindUserByNameByPsw(uname, upsw);
		pw.write(flag+"");
		pw.flush();
		pw.close();
//		if(flag){
//			resp.sendRedirect("main.jsp");
//		}else{
//			resp.sendRedirect("index.jsp");
//		} 
		}
	}
}
